<template>
  <div class="topologyLineEdit">
    <el-drawer v-model="drawer" v-if="drawer" class="drawer" :size="576">
      <template #header>
        <h4>关系</h4>
      </template>
      <template #default>
        <el-form
          :model="form"
          :rules="rules"
          ref="ruleFormRef"
          label-width="120px"
          label-position="top"
        >
          <el-form-item label="关系类型名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="属性" prop="">
            <el-table
              :data="form.propTable"
              style="width: 100%"
              max-height="300"
              ref="editTable"
            >
              <el-table-column label="属性名称" prop="name">
                <template v-slot="{ row, $index }">
                  <span v-if="!row.isEdit">{{ row.name }}</span>
                  <el-form-item
                    v-if="row.isEdit"
                    :prop="'propTable.' + $index + '.name'"
                    :key="$index"
                    :rules="[
                      {
                        validator: checkName,
                        trigger: 'change',
                      },
                    ]"
                  >
                    <el-input
                      type="text"
                      placeholder="请输入属性名"
                      v-model="row.name"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="数据类型" prop="dataType">
                <template v-slot="{ row }">
                  <span v-show="!row.isEdit">{{ row.dataType }}</span>
                  <el-select
                    v-show="row.isEdit"
                    v-model="row.dataType"
                    :disabled="row.code"
                  >
                    <el-option
                      v-for="item in dataTypeList"
                      :key="item.id"
                      :label="item.dictKey"
                      :value="item.dictKey"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template v-slot="{ row, $index }">
                  <el-button
                    size="small"
                    v-show="!row.isEdit"
                    @click="handleEdit($index, row)"
                    :disabled="tableDisabled"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    v-show="row.isEdit"
                    :disabled="
                      (tableDisabled && !row.isEdit) ||
                      isableSave ||
                      row.name.trim() == ''
                    "
                    @click="handleSave($index, row)"
                    >保存</el-button
                  >
                  <el-popover
                    :visible="row.visible"
                    placement="top"
                    trigger="click"
                    :width="160"
                  >
                    <p>确定删除吗?</p>
                    <div style="margin: 0; text-align: right">
                      <el-button size="small" text @click="row.visible = false"
                        >取消</el-button
                      >
                      <el-button
                        size="small"
                        type="primary"
                        @click="handleDelete(row, $index)"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <el-button
                        size="small"
                        type="danger"
                        :disabled="tableDisabled && !row.isEdit"
                        @click="row.visible = true"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          @click="handleAddAttr"
          :disabled="tableDisabled"
          >添加属性</el-button
        >
      </template>
      <template #footer>
        <div style="display: flex; justify-content: center">
          <el-button
            type="primary"
            @click="confirmClick(ruleFormRef)"
            :disabled="tableDisabled"
            :loading="comfirLoading"
            >保存</el-button
          >
          <el-button @click="cancelClick">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { deelSubmitData } from "@/views/buildKg/ontology/common/utils";
import { deelNode } from "./common/utils";
import G6 from "@antv/g6";

defineOptions({
  name: "topology-line-edit",
});
import { emitter } from "@/utils/mitt";
import type { FormRules, FormInstance } from "element-plus";
import type { Graph } from "@antv/g6";
import { graphSaveApi } from "@/api/buildKg/tology";
import { ElMessage } from "element-plus";
const graphModule: Ref<Graph> = inject("graphModule");
const dataTypeList = inject("dataTypeList");

interface PropTable {
  name: string;
  dataType: string;
  isEdit?: boolean;
  code?: string;
  visible?: Boolean;
}
let currentModel;
onMounted(() => {
  emitter.on("handleTologyLineEdit", (currentEvt) => {
    drawer.value = true;
    currentModel = currentEvt.item.getModel();
    form.name = currentModel.labelName || "";
    form.propTable = currentModel.propertyDTOList
      ? JSON.parse(JSON.stringify(currentModel.propertyDTOList))
      : [];
  });
});
/** 表单相关*/
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "名字不能为空", trigger: "blur" }],
});
const isableSave = ref(false);
const checkName = (rule: any, value: any, callback: any) => {
  let validReg = /^[\u4E00-\u9FA5a-zA-Z0-9_]{1,63}$/;
  if (value.trim() === "") {
    isableSave.value = true;
    callback(new Error("属性不能为空"));
  } else if (!validReg.test(value)) {
    callback(
      new Error(
        "属性名称只能由大小写字母、数字、中文、下划线组成，长度为1-63位"
      )
    );
  } else {
    let vaildArr = form.propTable.slice(0, form.propTable.length - 1);
    let falg = false;
    vaildArr.forEach((item) => {
      if (item.name.trim() === value.trim()) {
        falg = true;
      }
    });
    if (falg) {
      isableSave.value = true;
      callback(new Error("属性不能重复"));
    } else {
      isableSave.value = false;
      callback();
    }
  }
};
let form = reactive({
  name: "",
  propTable: [],
});

/** 表格相关*/
// let propTable: Ref<PropTable[]> = ref([]);

//新增数据
const editTable = ref();
const handleAddAttr = () => {
  form.propTable.push({
    name: "",
    dataType: "string",
    isEdit: true,
  });
  nextTick(() => {
    let ScrollTop = 56.5 * form.propTable.length;
    editTable.value.setScrollTop(ScrollTop);
  });
};
const handleEdit = (index: number, row: PropTable) => {
  row.isEdit = true;
};
const handleSave = (index: number, row: PropTable) => {
  row.isEdit = false;
};
const handleDelete = (row: PropTable, index: number) => {
  row.visible = false;
  form.propTable.splice(index, 1);
};

let tableDisabled = computed(() => {
  return !!form.propTable.filter((item) => item.isEdit)?.length;
});
//抽屉相关
let drawer = ref(false);
function cancelClick() {
  reset();
}
const reset = () => {
  form.propTable = [];
  form.name = "";
  drawer.value = false;
};
let layout = ref("");
emitter.on("graphLayoutActive", (type) => {
  layout.value = type;
});
let comfirLoading = ref(false);
const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      currentModel.propertyDTOList = form.propTable;
      currentModel.labelName = form.name;
      currentModel.label = form.name;
      let graphData = graphModule.value.save();
      let graphDeelData = deelSubmitData(graphData, layout.value);
      comfirLoading.value = true;
      let res = await graphSaveApi(graphDeelData).catch(() => {
        comfirLoading.value = false;
      });
      if (res.code === 200) {
        let renderData = res.data as Record<string, any>;
        deelNode(renderData);
        renderData?.edges && G6.Util.processParallelEdges(renderData.edges);
        graphModule.value.data(renderData);
        graphModule.value.render();
        ElMessage.success("保存成功");
        reset();
        comfirLoading.value = false;
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

onUnmounted(() => {
  emitter.off("handleTologyLineEdit");
  emitter.off("graphLayoutActive");
});
</script>

<style scoped lang="scss">
.up-color {
  width: 100%;
  padding: 6px 12px;
  line-height: 22px;
  text-align: center;
  border: 1px solid #adb0b8;

  .circle.activate {
    cursor: pointer;
    border: 2px solid #5e7ce0;
  }

  .circle {
    display: inline-block;
    width: 22px;
    height: 22px;
    margin: 0 3px;
    border: 2px solid #fff;
    border-radius: 50%;

    &:hover {
      cursor: pointer;
      border: 2px solid #5e7ce0;
    }

    .color {
      position: relative;
      top: 0;
      display: inline-block;
      width: 14px;
      height: 14px;
      border-radius: 50%;
    }
  }
}

.topologyLineEdit {
  ::v-deep .el-drawer {
    .el-table {
      .cell {
        padding-bottom: 14px;
        overflow: visible;
      }

      .el-form-item {
        .el-form-item__error {
          overflow: visible;
          white-space: nowrap;
        }
      }
    }

    .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
      background-color: transparent;
    }
  }
}
</style>
